import axios, { AxiosInstance, AxiosError, AxiosResponse, InternalAxiosRequestConfig } from 'axios';

const baseURL = "http://127.0.0.1:8888/"
const service: AxiosInstance = axios.create({
    timeout: 5000,
    baseURL: baseURL
});

// 请求拦截器
service.interceptors.request.use(
    (config: InternalAxiosRequestConfig) => {
        let access_token = window.localStorage.getItem('token')
        let refresh_token = window.localStorage.getItem('refresh_token')
        if (config.url === '/api/token/refresh') {
            config.headers.Authorization = 'Bearer ' + refresh_token
            return config;
        } else if(access_token) {
            config.headers.Authorization = 'Bearer ' + access_token
            return config;
        } else {
            return config;
        }
        // return config
    },
    (error: AxiosError) => {
        return Promise.reject();
    }
);

// 响应拦截器
service.interceptors.response.use(
    (response: AxiosResponse) => {
        if (response.status === 200 || response.status===202) {
            return response;
        } else {
            Promise.reject();
        }
    },
    (error: AxiosError) => {
        return Promise.reject(error)
    }
);

export default service;
